package com.stary.music.api.source.qq;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.stary.music.api.vo.MusicInfo;
import com.stary.music.exception.MyMusicException;
import com.stary.music.util.HTTPUtils;
import com.stary.music.util.PropertiesUtils;

/**
 * qq音乐API
 * @author stary
 * @date 2018年6月15日 上午10:26:16
 */
public class QQMusic {

	private static final Logger logger=LoggerFactory.getLogger(QQMusic.class);
	private static final String PREFIX="qq.music";	
	private static PropertiesUtils pUtils=null;	 
	static {
		pUtils=new PropertiesUtils();
		pUtils.setKeyPrefix(PREFIX);
	}
	/**
	 * 根据关键词搜索歌曲信息 <br>
	 * 关键词：歌曲名、专辑、歌手 
	 * @param searchRequest
	 * @return
	 */
	public List<MusicInfo> searchMusicList(QQSearchRequest searchRequest){
		if(searchRequest.getW()==null || searchRequest.getW().isEmpty()){
			logger.error("缺少参数或出现不能识别的参数");
			throw new MyMusicException("a parameter is missing or unrecognized");
		}
		List<MusicInfo> list=null;
		StringBuffer buffer=new StringBuffer();
		JSONObject searchRequestJSON=(JSONObject) JSONObject.toJSON(searchRequest);
		for (Entry<?, ?> entry : searchRequestJSON.entrySet()) {
			buffer.append("&" + entry.getKey() + "=" + entry.getValue());
		}
		buffer.replace(0, 1, "");
		logger.debug("搜索歌曲信息入参----->>{}",buffer.toString());
		pUtils.setKey("search");
		Map<String, String> headerMap=new HashMap<>();
		// 禁止跨域访问
		headerMap.put("host", "c.y.qq.com");
		headerMap.put("Referer", "https://c.y.qq.com/");
		try {
			String resp=HTTPUtils.sendGet(pUtils.getStringValue(),headerMap, buffer.toString());
			logger.debug("搜索歌曲信息出参----->>{}",resp);
			if(!resp.isEmpty()){
				JSONObject respJSON = JSONObject.parseObject(resp);
				if(respJSON.getInteger("code")==0 && respJSON.containsKey("data")){
					String data = respJSON.getString("data");
					JSONObject dataJSON = JSONObject.parseObject(data);
					if (dataJSON.containsKey("song")) {
						String songs = dataJSON.getString("song");
						JSONObject songsJSON = JSONObject.parseObject(songs);
						if (songsJSON.containsKey("list")) {
							JSONArray listJSONArray = songsJSON.getJSONArray("list");
							list=new ArrayList<MusicInfo>();
							MusicInfo info=null;
							for (int i = 0; i < listJSONArray.size(); i++) {
								String song=listJSONArray.getString(i);
								JSONObject songJSON = JSONObject.parseObject(song);
								info=new MusicInfo();
								// 歌名
								String name=songJSON.getString("songname");
								info.setName(name);
								// ID
								String id=songJSON.getString("songid");
								info.setId(id);
								// 专辑 
								String album=songJSON.getString("albumname");
								info.setAlbum(album);
								// 歌手
								JSONArray singerJSONArray = songJSON.getJSONArray("singer");
								StringBuffer artist = new StringBuffer();
								for (int j = 0; j < singerJSONArray.size(); ++j) {
									String singer = singerJSONArray.getString(j);
									JSONObject singerJSON = JSONObject.parseObject(singer);
									artist.append(singerJSON.getString("name"));									
									if (j < singerJSONArray.size() - 1) {
										artist.append("/");										
									}
								}
								info.setSinger(artist.toString());
								// 封面
								String albummid = songJSON.getString("albummid");
								pUtils.setKey("cover");
								String cover=pUtils.getStringValue().replace("ALBUMMID", albummid);
								info.setCover(cover);
								// 外链
								String songmid=songJSON.getString("songmid");
								info.setMid(songmid);
								//pUtils.setKey("src");
								//String src=pUtils.getStringValue().replace("SONGMID", songmid);
								//info.setSrc(src);
								if(searchRequest.getShowLrc()!=0){
									String lyric=getMusicLyric(songmid,id);
									info.setLyric(lyric);
								}
								list.add(info);
							}
						}
					}	
				}
			}
		} catch (Exception e) {
			logger.error("搜索歌曲信息出现异常",e);
		}
		return list;
	}
	/**
	 * 获取外链
	 * @param mid
	 * @return
	 */
	public String getMusicSrc(String mid){
		pUtils.setKey("src");
		return pUtils.getStringValue().replace("SONGMID", mid);
	}
	/**
	 * 获取歌词信息 
	 * @param songmid 媒体ID
	 * @param id ID
	 * @return
	 */
	public String getMusicLyric(String songmid,String id){
		String lyric="";
		pUtils.setKey("infopage");
		Map<String, String> headerMap=new HashMap<String,String>();
		// 禁止跨域访问
		headerMap.put("host", "c.y.qq.com");
		headerMap.put("Referer", pUtils.getStringValue().replace("SONGMID", songmid));			
		pUtils.setKey("lyric");
		try {
			String resp=HTTPUtils.sendGet(pUtils.getStringValue(), headerMap, "nobase64=1&musicid="+id);
			
			if(!resp.isEmpty()){
					resp=resp.replace("MusicJsonCallback(", "").replace(")", "");
					// 转义特殊字符
					resp=StringEscapeUtils.unescapeHtml3(resp);
					logger.debug("搜索歌词信息出参----->>{}",resp);
					JSONObject respJSON=JSONObject.parseObject(resp);
					if(respJSON.getInteger("code")==0){
						lyric=respJSON.getString("lyric");
					}
			}
		} catch (Exception e) {
			logger.error("获取歌词信息出现异常",e);
		}
		return lyric;
	}
	/**
	 * 获取外链 vkey
	 * @param mid
	 * @return
	 */
	public String getMusicSrcVkey(String mid){
		String src="";
		long guid=System.currentTimeMillis();
		String cid="205361747";
		pUtils.setKey("src_vkey");
		String resp=HTTPUtils.sendGet(pUtils.getStringValue(),"format=json205361747&platform=yqq&cid="+cid+"&songmid="+mid+"&filename=C400"+mid+".m4a&guid="+guid);
		logger.debug("获取外链vkey出参----->>{}",resp);
		if(!resp.isEmpty()){
			JSONObject respJSON = JSONObject.parseObject(resp);
			if(respJSON.getInteger("code")==0 && respJSON.containsKey("data")){
				String data = respJSON.getString("data");
				JSONObject dataJSON = JSONObject.parseObject(data);
				JSONArray itemsJSONArray = dataJSON.getJSONArray("items");
				String item=itemsJSONArray.getString(0);
				JSONObject itemJSON = JSONObject.parseObject(item);
				String vkey=itemJSON.getString("vkey");
				String filename=itemJSON.getString("filename");
				pUtils.setKey("playsrc");
				src= pUtils.getStringValue().replace("FILENAME", filename).replace("GUID", String.valueOf(guid)).replace("VKEY", vkey);
				
			}
		}
		return src;
	}

}
